﻿
using Core.Configuration.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Core.Configuration.Startup
{
    /// <summary>
    /// 全局JSON结果封装
    /// </summary>
    public class GlobalResultFilter : IResultFilter
    {
        public void OnResultExecuted(ResultExecutedContext context)
        {
            
        }

        public void OnResultExecuting(ResultExecutingContext context)
        {
            //double newValue = 3.10;
            //context.Result = new ObjectResult(new
            //{
            //    newValue = newValue
            //});

            if (context.Result is ObjectResult)
            {
                var result = (ObjectResult)context.Result;
                var apiResult = new ApiResult()
                {
                    status = 200,
                    message = "success",
                    data = result.Value
                };

                if (result.StatusCode != null && result.StatusCode != 200)
                {
                    var validation = (ValidationProblemDetails)result.Value;
                    apiResult.status = result.StatusCode ?? 500;
                    apiResult.message = validation.Title;
                }
                context.Result = new ObjectResult(apiResult);
            }
            else if (context.Result is JsonResult)
            {
                var result = (JsonResult)context.Result;
                context.Result = new JsonResult(new ApiResult
                {
                    status = 200,
                    message = "success",
                    data = result.Value
                });
            }
        }
    }    
}